package solution;

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
        next = null;
    }
}

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int len1 = 0;
        int len2 = 0;

        ListNode cur = headA;
        while (cur != null) {
            cur = cur.next;
            len1++;
        }

        cur = headB;
        while (cur != null) {
            cur = cur.next;
            len2++;
        }

        ListNode cur1 = headA;
        ListNode cur2 = headB;

        int sub = Math.abs(len1 - len2);
        while (sub > 0 && cur1 != null && cur2 != null) {
            if (len1 > len2) {
                cur1 = cur1.next;
            } else if (len1 < len2) {
                cur2 = cur2.next;
            }
            sub--;
        }

        while (cur1 != null && cur2 != null) {
            if (cur1 == cur2) {
                return cur1;
            }
            cur1 = cur1.next;
            cur2 = cur2.next;
        }

        return null;
    }
}